<?php
class ControllerSaleVdiVendorBill extends Controller {
  private $error = array();

  public function export(){
    $vendor_bill_id = I('get.vendor_bill_id');
    if(!$vendor_bill_id){
      $vendor_bill_id = 0;
    }
    $this->load->model('sale/vendor_bill');
    $vendor_bill = $this->model_sale_vendor_bill->getVendorBill($vendor_bill_id);
    $data['vendor_bill'] = $vendor_bill;
    if(!$vendor_bill){
      $this->load->language('error/not_found');
 
      $this->document->setTitle($this->language->get('heading_title'));

      $data['heading_title'] = $this->language->get('heading_title');
 
      $data['text_not_found'] = $this->language->get('text_not_found');
 
      $data['breadcrumbs'] = array();

      $data['breadcrumbs'][] = array(
        'text' => $this->language->get('heading_title'),
        'href' => $this->url->link('error/not_found', 'token=' . $this->session->data['token'], 'SSL')
      );

      $data['footer'] = $this->load->controller('common/footer');
 
      $this->response->setOutput($this->load->view('error/not_found.tpl', $data));
    }
    $vendor_bill_po = $this->model_sale_vendor_bill->getVendorBillPo($vendor_bill_id);
    $po_num = $this->model_sale_vendor_bill->getVendorBillPoCount($vendor_bill_id);
    $po_num = count($po_num);
    $vendor_info = $this->model_sale_vendor_bill->getVendorByVendorBillId($vendor_bill_id);

    $po_total = $vendor_bill_po[0]['total'];

    $this->load->library('PHPExcel/PHPExcel');
    $objReader = PHPExcel_IOFactory::createReader('Excel5');
    $objPHPExcel = $objReader->load(DIR_SYSTEM . "template/vendor_bill_tpl.xls"); 
    $objPHPExcel->getProperties()->setCreator("Think-tec")
               ->setLastModifiedBy("Think-tec")
               ->setTitle("BHZ品牌厂商对账单")
               ->setSubject("BHZ品牌厂商对账单")
               ->setDescription("BHZ品牌厂商对账单")
               ->setKeywords("BHZ, Think-tec")
               ->setCategory("Think-tec");
    // $objPHPExcel->setActiveSheetIndex(0);
    $objActSheet = $objPHPExcel->getActiveSheet();

    $objActSheet->setCellValue('B2', $vendor_bill_po[0]['date_added']);
    $objPHPExcel->getActiveSheet()->getStyle('B2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    $objActSheet->setCellValue('F2', $vendor_info['vendor_id']);
    $objActSheet->setCellValue('B3', $vendor_bill_po[0]['vendor_bill_id']);
    
    $objActSheet->setCellValue('F3', $vendor_info['vendor_name']);
    $objActSheet->setCellValue('F4', $vendor_info['firstname']);
    $objActSheet->setCellValue('F5', $vendor_info['telephone']);

    $objActSheet->setCellValue('D7', $po_num);
    $objActSheet->setCellValue('F7', '￥'.$po_total);

    $row_num = 8;
    $styleBorderOutline = array(
      'borders' => array(
        'outline' => array(
          'style' => PHPExcel_Style_Border::BORDER_THIN,
        ),
      ),
    );
    $objPHPExcel->getActiveSheet()->insertNewRowBefore(9, count($vendor_bill_po));
    $count = 0;
    foreach ($vendor_bill_po as $key => $po_pd_info) {
      $row_num++;
      $objActSheet->setCellValue('A'.$row_num, $row_num-8);
      $objActSheet->setCellValue('B'.$row_num, $po_pd_info['name'] . ' - ' . $po_pd_info['option_name']);
      $objActSheet->setCellValue('C'.$row_num, '');
      $objActSheet->setCellValue('D'.$row_num, $po_pd_info['qty']);
      $objActSheet->setCellValue('E'.$row_num, $po_pd_info['unit_price']);
      $objActSheet->setCellValue('F'.$row_num, $po_pd_info['price']);
    }
    // $objPHPExcel->getActiveSheet()->getStyle('A5'.':'.'O'.$row_num)->applyFromArray($styleBorderOutline);
    
    $objActSheet->setTitle('品牌厂商对账单');


    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    ob_end_clean();
    // Redirect output to a client’s web browser (Excel2007)
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="VD_BILL_BHZ_'.date('Y-m-d-H-i',time()).'.xlsx"');
    header('Cache-Control: max-age=0');
    // If you're serving to IE 9, then the following may be needed
    header('Cache-Control: max-age=1');
    // If you're serving to IE over SSL, then the following may be needed
    header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
    header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
    header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
    header ('Pragma: public'); // HTTP/1.0
    $objWriter->save('php://output'); 
    exit;
  }

  public function index() {

    $this->document->setTitle('品牌厂商对账单');

    $this->load->model('sale/vendor_bill');

    $this->getList();
  }

  public function view(){

    $this->document->setTitle('查看品牌厂商对账单');

    $this->document->addScript('view/javascript/angular.js');
    $this->document->addScript('view/javascript/bhz_ctl.js');

    $this->load->model('sale/vendor_bill');
    $data['breadcrumbs'] = array();

    $data['breadcrumbs'][] = array(
      'text' => $this->language->get('text_home'),
      'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
    );

    $data['breadcrumbs'][] = array(
      'text' => '品牌厂商对账单',
      'href' => $this->url->link('sale/vendor_bill', 'token=' . $this->session->data['token'] , 'SSL')
    );

    $data['token'] = $this->session->data['token'];

    $id = I('get.vendor_bill_id');
    if(!$id){
      $id=0;
    }
    

    if (isset($this->session->data['error'])) {
      $data['error_warning'] = $this->session->data['error'];

      unset($this->session->data['error']);
    } elseif (isset($this->error['warning'])) {
      $data['error_warning'] = $this->error['warning'];
    } else {
      $data['error_warning'] = '';
    }

    if (isset($this->session->data['success'])) {
      $data['success'] = $this->session->data['success'];

      unset($this->session->data['success']);
    } else {
      $data['success'] = '';
    }
    
    $vendor_bill = $this->model_sale_vendor_bill->getVendorBill($id);
    $data['vendor_bill'] = $vendor_bill;
    $vendor_bill_po = $this->model_sale_vendor_bill->getVendorBillPo($id);
    $data['vendor_bill_po'] = $vendor_bill_po;
    $vendor_bill_histories = $this->model_sale_vendor_bill->getVendorBillHistories($id);
    $data['vendor_bill_histories'] = $vendor_bill_histories;

    switch ($vendor_bill['status']) {
      // case '0':
      //   $data['change_status_text'] = '平台确认对账单';
      //   break;
      case '1':
        $data['change_status_text'] = '品牌厂商确认对账单';
        break;
      // case '2':
      //   $data['change_status_text'] = '已打款';
      //   break;
      case '3':
        $data['change_status_text'] = '已收款';
        break;
      // case '4':
      //   $data['change_status_text'] = '已完成';
      //   break;
      default:
        $data['change_status_text'] = '';
        break;
    }

    $data['header'] = $this->load->controller('common/header');
    $data['column_left'] = $this->load->controller('common/column_left');
    $data['footer'] = $this->load->controller('common/footer');

    $this->response->setOutput($this->load->view('sale/vdi_vendor_bill_view.tpl', $data));
  }

  public function save(){
    if ($this->request->server['REQUEST_METHOD'] == 'POST') {
      $this->load->model('sale/vendor_bill');
      $data = json_decode(file_get_contents('php://input'), true);
      $filter = C('DEFAULT_FILTER');
      $data   =   is_array($data) ? array_map_recursive($filter,$data) : $filter($data);
      if(!$data['deliver_time'] || !$data['products']||!$data['vendor']){
        $this->response->setOutput(json_encode(array('success'=>false, 'info'=>'数据不完整')));
      }
      else{
        $po_id = $this->model_sale_vendor_bill->addPo($data, $this->user->getId());
      }
      $this->response->setOutput(json_encode(array('success'=>true, 'info'=>$po_id)));
      return;
    }
  }

  public function delete() {
    $json = array();

    $this->load->model('sale/vendor_bill');

    $id = I('get.vendor_bill_id');
    if(!$id){
      $id=0;
    }
    
    $vendor_bill = $this->model_sale_vendor_bill->getVendorBill($id);
    if(!$vendor_bill||$vendor_bill['status']!=0) {
      $json['error'] = '非新增状态品牌厂商对账单不能删除';
    }
    else {
      $this->model_sale_vendor_bill->deleteBill($id);
      $json['success'] = '删除成功';
    }

    if (isset($this->request->server['HTTP_ORIGIN'])) {
      $this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
      $this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
      $this->response->addHeader('Access-Control-Max-Age: 1000');
      $this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
    }

    $this->response->addHeader('Content-Type: application/json');
    $this->response->setOutput(json_encode($json));
  }

  protected function form(){
    $data['breadcrumbs'] = array();

    $data['breadcrumbs'][] = array(
      'text' => $this->language->get('text_home'),
      'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
    );

    $data['breadcrumbs'][] = array(
      'text' => '品牌厂商对账单',
      'href' => $this->url->link('sale/vendor_bill', 'token=' . $this->session->data['token'] , 'SSL')
    );

    $data['token'] = $this->session->data['token'];

    $id = I('get.po_id');
    if(!$id){
      $id=0;
    }
    

    if (isset($this->session->data['error'])) {
      $data['error_warning'] = $this->session->data['error'];

      unset($this->session->data['error']);
    } elseif (isset($this->error['warning'])) {
      $data['error_warning'] = $this->error['warning'];
    } else {
      $data['error_warning'] = '';
    }

    if (isset($this->session->data['success'])) {
      $data['success'] = $this->session->data['success'];

      unset($this->session->data['success']);
    } else {
      $data['success'] = '';
    }
    
    $po = $this->model_sale_vendor_bill->getPo($id);
    $data['po'] = $po;
    $po_products = $this->model_sale_vendor_bill->getPoProducts($id);
    $data['po_products'] = $po_products;

    $data['header'] = $this->load->controller('common/header');
    $data['column_left'] = $this->load->controller('common/column_left');
    $data['footer'] = $this->load->controller('common/footer');

    $this->response->setOutput($this->load->view('sale/vendor_bill.tpl', $data));
  }

  

  protected function getList() {
    $page = I('get.page');
    if(!$page){
      $page = 1;
    }
    $filter_vendor_bill_id = I('get.filter_vendor_bill_id');
    $filter_vendor_name = I('get.filter_vendor_name');
    $filter_year_month = I('get.filter_year_month');
    $filter_total = I('get.filter_total');
    $filter_date_added = I('get.filter_date_added');
    $filter_vendor_bill_status = I('get.filter_vendor_bill_status');
    
    if($filter_vendor_bill_id) {$filter['vendor_bill_id'] = $filter_vendor_bill_id;}
    // if($filter_vendor_name) {$filter['vendor_name'] = array('like', '%'.$filter_vendor_name.'%');}
    if($filter_year_month) {$filter['DATE_FORMAT(vb.year_month, "%Y-%m")'] = $filter_year_month;}
    if($filter_total) {$filter['total'] = $filter_total;}
    if($filter_date_added) {$filter['date_added'] = $filter_date_added;}
    if($filter_vendor_bill_status || $filter_vendor_bill_status==0) {
      $filter['vb.status'] = $filter_vendor_bill_status;
    }

    $data['filter_vendor_bill_id'] = $filter_vendor_bill_id;
    // $data['filter_vendor_name'] = $filter_vendor_name;
    $data['filter_year_month'] = $filter_year_month;
    $data['filter_total'] = $filter_total;
    $data['filter_date_added'] = $filter_date_added;
    $data['filter_vendor_bill_status'] = $filter_vendor_bill_status;

    if($filter_vendor_bill_status=='') {
      unset($data['filter_vendor_bill_status']);  
      unset($filter['vb.status']);
    }

    $sort = I('get.sort');
    $order = I('get.order');
    if($order) {
      $order = $order=='DESC'?'ASC':'DESC';
    }

    $sort_data = array(
      'sort' => $sort?$sort:'vendor_bill_id',
      'order' => $order?$order:'DESC',
    );

    $data['order'] = $sort_data['order'];
    $data['sort'] = $sort_data['sort'];

    $url .= '&order=' . $sort_data['order'];

    $data['sort_vendor_bill'] = $this->url->link('sale/vendor_bill', 'token=' . $this->session->data['token'] . '&sort=vb.vendor_bill_id' . $url, 'SSL');
    $data['sort_vendor_name'] = $this->url->link('sale/vendor_bill', 'token=' . $this->session->data['token'] . '&sort=vb.vendor_name' . $url, 'SSL');
    $data['sort_status'] = $this->url->link('sale/vendor_bill', 'token=' . $this->session->data['token'] . '&sort=vb.status' . $url, 'SSL');
    $data['sort_year_month'] = $this->url->link('sale/vendor_bill', 'token=' . $this->session->data['token'] . '&sort=vb.year_month' . $url, 'SSL');
    $data['sort_date_added'] = $this->url->link('sale/vendor_bill', 'token=' . $this->session->data['token'] . '&sort=vb.date_added' . $url, 'SSL');
    $data['sort_date_modified'] = $this->url->link('sale/vendor_bill', 'token=' . $this->session->data['token'] . '&sort=vb.date_modified' . $url, 'SSL');

    
    if($this->user->getVp()){
      $filter['vb.vendor_id'] = $this->user->getVp();
    }
    else{
      
    }

    $vendor_bill_list =  $this->model_sale_vendor_bill->getList($page, $filter, $sort_data);
    $bill_total = $this->model_sale_vendor_bill->getListCount($filter);
    foreach ($vendor_bill_list as $key => $value) {
      $vendor_bill_list[$key]['status_name'] = getVendorBillStatus()[$value['status']];
    }

    $pagination = new Pagination();
    $pagination->total = $bill_total;
    $pagination->page = $page;
    $pagination->limit = $this->config->get('config_limit_admin');
    $pagination->url = $this->url->link('sale/vendor_bill', 'token=' . $this->session->data['token'] . '&page={page}', 'SSL');

    $data['pagination'] = $pagination->render();

    $data['breadcrumbs'] = array();

    $data['breadcrumbs'][] = array(
      'text' => $this->language->get('text_home'),
      'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
    );

    $data['breadcrumbs'][] = array(
      'text' => '品牌厂商对账单',
      'href' => $this->url->link('sale/vendor_bill', 'token=' . $this->session->data['token'] , 'SSL')
    );

    if (isset($this->session->data['error'])) {
      $data['error_warning'] = $this->session->data['error'];

      unset($this->session->data['error']);
    } elseif (isset($this->error['warning'])) {
      $data['error_warning'] = $this->error['warning'];
    } else {
      $data['error_warning'] = '';
    }

    if (isset($this->session->data['success'])) {
      $data['success'] = $this->session->data['success'];

      unset($this->session->data['success']);
    } else {
      $data['success'] = '';
    }

    $data['vendor_bill_statuses'] = getVendorBillStatus();

    $data['token'] = $this->session->data['token'];
    
    $data['vendor_bills'] = $vendor_bill_list;

    $data['header'] = $this->load->controller('common/header');
    $data['column_left'] = $this->load->controller('common/column_left');
    $data['footer'] = $this->load->controller('common/footer');

    $this->response->setOutput($this->load->view('sale/vdi_vendor_bill_list.tpl', $data));
  }

  public function setVendorBillDiff() {
    if ($this->request->server['REQUEST_METHOD'] == 'POST') {
      $this->load->model('sale/vendor_bill');
      $data = json_decode(file_get_contents('php://input'), true);
      $filter = C('DEFAULT_FILTER');
      $data   =   is_array($data) ? array_map_recursive($filter,$data) : $filter($data);
      // $id = I('post.po_id');
      $id = $data['vendor_bill_id'];
      if(!$id){
        $id=0;
      }
      $vendor_bill = $this->model_sale_vendor_bill->getVendorBill($id);
      //判断vendor_bill状态，如果是物流中心确认之后的状态则不允许在添加差额
      if($vendor_bill['status'] > 1) {
        $this->response->setOutput(json_encode(array('error'=>'不能修改物流中心确认之后的差价')));
        return;
      }

      $difference = $data['difference'];
      if($difference) {
        $difference = (float)$difference;
        $this->model_sale_vendor_bill->changeDifference($id, $difference);
        $this->response->setOutput(json_encode(array('success'=>'修改对账单差价状态成功')));
      } else {
        $this->response->setOutput(json_encode(array('error'=>'差价不能为空')));
      }
      return;

      $this->response->setOutput(json_encode(array('success'=>'修改采购单状态成功')));
      return;
    } 
  }

  public function changeVendorBillStatus() {
    if ($this->request->server['REQUEST_METHOD'] == 'POST') {
      $this->load->model('sale/vendor_bill');
      $data = json_decode(file_get_contents('php://input'), true);
      $filter = C('DEFAULT_FILTER');
      $data   =   is_array($data) ? array_map_recursive($filter,$data) : $filter($data);
      // $id = I('post.po_id');
      $id = $data['vendor_bill_id'];
      if(!$id){
        $id=0;
      }
      $vendor_bill = $this->model_sale_vendor_bill->getVendorBill($id);

      switch ($vendor_bill['status']) {
        case '0':
          $target_status = 1;
          break;
        case '1':
          $target_status = 2;
          break;
        case '2':
          $target_status = 3;
          break;
        case '3':
          $target_status = 4;
          break;
        case '4':
          $target_status = 5;
          break;
        default:
          $target_status = -1;
          break;
      }
      if($target_status == -1) {
        $this->response->setOutput(json_encode(array('error'=>'修改对账单状态失败')));
      } else {
        $this->model_sale_vendor_bill->changeVendorBillStatus($id, $target_status);
        $this->response->setOutput(json_encode(array('success'=>'修改对账单状态成功')));

        //添加生成品牌商对账单操作记录
        $this->load->model('catalog/vendor');
        $vendor_info = $this->model_catalog_vendor->getVendorByUserId($this->user->getId());
        $comment = '修改对账单状态为：'.getVendorBillStatus()[$target_status];
        $this->model_sale_vendor_bill->addVendorBillHistory($id, $this->user->getId(), $vendor_info['vendor_name'], $comment);  
      }
      return;
    } 
  }

}